using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;
using Microsoft.SharePoint.Utilities;

namespace LanguageConfigurationSolution
{
    class AllowPageLayoutInlineCodeFeatureReceiver : SPFeatureReceiver
    {
        private void ApplyWebConfigModificationsToFarm(SPWebApplication webApp)
        {
            try
            {
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (System.UnauthorizedAccessException ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry(this.GetType().FullName, string.Format("Exception occured running the FeatureReceiver when ApplyWebConfigModifications was called.{0}If you give WSS_WPG user account full permission to the config folder the error will disappear!{0}{1}", Environment.NewLine, ex.ToString()), EventLogEntryType.Error);
                });
                throw;
            }
        }

        private string Owner
        {
            get
            {
                return this.GetType().FullName + ", " + this.GetType().Assembly.FullName;
            }
        }

        private SPWebConfigModification AddPageParserPaths_modification
        {
            get
            {
                SPWebConfigModification modification = new SPWebConfigModification("PageParserPaths", "configuration/SharePoint/SafeMode");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                modification.Value = string.Format("<PageParserPaths></PageParserPaths>");
                modification.Owner = string.Empty;
                return modification;
            }
        }

        private SPWebConfigModification AddPageParserPath_modification(SPSite site)
        {
                string Virtualpath = SPUrlUtility.CombineUrl(site.RootWeb.RootFolder.ServerRelativeUrl, "/_catalogs/masterpage/*"); 
                SPWebConfigModification modification = new SPWebConfigModification(string.Format("PageParserPath[@VirtualPath='{0}']",Virtualpath), "configuration/SharePoint/SafeMode/PageParserPaths");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                modification.Value = string.Format("<PageParserPath VirtualPath=\"{0}\" CompilationMode=\"Always\" AllowServerSideScript=\"true\" />",Virtualpath);
                modification.Owner = Owner;
                return modification;
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            if (site == null) return;

            SPWebApplication webapp = site.WebApplication;
            webapp.WebConfigModifications.Add(AddPageParserPaths_modification);
            webapp.WebConfigModifications.Add(AddPageParserPath_modification(site));

            webapp.Update(); // Important. Otherwise webconfigmods can be removed upon activating other features
            ApplyWebConfigModificationsToFarm(webapp);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            if (site == null) return;

            SPWebApplication webapp = site.WebApplication;

            for (int idx = webapp.WebConfigModifications.Count - 1; idx >= 0; idx--)
            {
                SPWebConfigModification conmod = webapp.WebConfigModifications[idx];
                string Virtualpath = SPUrlUtility.CombineUrl(site.RootWeb.RootFolder.ServerRelativeUrl, "/_catalogs/masterpage/*"); 
                if (string.Compare(conmod.Owner, Owner, true) == 0 && conmod.Value.Contains(string.Format("VirtualPath=\"{0}\"",Virtualpath)))
                {
                    webapp.WebConfigModifications.RemoveAt(idx);
                }
            }

            webapp.Update(); // Important
            ApplyWebConfigModificationsToFarm(webapp);

        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

    }
}
